package com.bi.onlineEducation.web.controller;

import com.bi.onlineEducation.annotation.WebProcess;
import com.bi.onlineEducation.dao.CourseDao;
import com.bi.onlineEducation.dao.CoursePathDao;
import com.bi.onlineEducation.domain.CoursePathPo;
import com.bi.onlineEducation.domain.CoursePo;
import com.bi.onlineEducation.exception.BusinessHandleException;
import com.bi.onlineEducation.service.CourseService;
import com.bi.onlineEducation.utils.FtpUtil;
import com.bi.onlineEducation.utils.ResultCode;
import com.bi.onlineEducation.web.constant.OEConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author: chenYuTao
 * @Time: 2022/1/6 15:44
 * @Description: 基础数据控制层
 **/
@Slf4j
@RestController
@Api(tags = "课程信息控制层", description = "课程信息数据接口")
public class CourseController {

    @Resource
    private CourseService courseService;
    @Resource
    private CourseDao courseDao;
    @Resource
    private CoursePathDao coursePathDao;
    @Resource
    private FtpUtil ftpUtil;

    @ApiOperation("查询所有")
    @WebProcess
    @GetMapping(value = "/course/findAll")
    public ResultCode findAll() {
        return ResultCode.success(courseService.findAll());
    }

    @ApiOperation("查询所有已上架")
    @WebProcess
    @GetMapping(value = "/course/findAllByCStatus")
    public ResultCode finfindAllByCStatusdAll() {
        return ResultCode.success(courseDao.findAllBycStatus(true));
    }

    @ApiOperation("根据id查询课程信息")
    @WebProcess
    @GetMapping(value = "/course/findById")
    public ResultCode findById(@RequestParam("id") Integer id) {
        return ResultCode.success(courseService.findById(id));
    }

    @ApiOperation("根据lid查询课程信息")
    @WebProcess
    @GetMapping(value = "/course/findAllByLId")
    public ResultCode findAllByLId(@RequestParam("lId") Integer lId) {
        return ResultCode.success(courseService.findAllByLId(lId));
    }

    @ApiOperation("订单搜索所有")
    @WebProcess
    @GetMapping(value = "/course/search")
    public ResultCode search(@RequestParam("cName") String cName, @RequestParam("cStatus") Integer cStatus) {
        return ResultCode.success(courseService.search(cName, cStatus));
    }

    @ApiOperation("包含当前用户订单搜索")
    @WebProcess
    @GetMapping(value = "/course/searchBylId")
    public ResultCode searchBylId(@RequestParam("cName") String cName, @RequestParam("cStatus") Integer cStatus
            , @RequestParam("lId") Integer lId) {
        return ResultCode.success(courseService.searchBylId(cName, cStatus, lId));
    }

    @ApiOperation("保存")
    @WebProcess
    @PostMapping(value = "/course/save")
    public ResultCode save(@RequestBody CoursePo coursePo) {
        Optional.ofNullable(StringUtils.isBlank(coursePo.getWatchPath()) ? null : "").orElseThrow(() -> BusinessHandleException.buildBizException("源视频解析失败，请重试"));
        Boolean isAdd = false;
        CoursePo oldCoursePo = null;
        if (coursePo.getCId() != null) {
            oldCoursePo = courseDao.findById(coursePo.getCId()).get();
            if (StringUtils.isNotBlank(coursePo.getWatchPath()) && !oldCoursePo.getWatchPath().equals(coursePo.getWatchPath())) {
                // 文件替换
                String oldFileName = oldCoursePo.getWatchPath().split("/")[oldCoursePo.getWatchPath().split("/").length - 1];
                String newFileName = coursePo.getWatchPath().split("/")[coursePo.getWatchPath().split("/").length - 1];
                ftpUtil.deleteFile(oldFileName);
                log.info("已删除文件名={},替换新的文件名为：{}", oldFileName, newFileName);
            }
        } else {
            isAdd = true;
            coursePo.setCStatus(false).setCreateTime(new Date());
        }
        CoursePo save = courseService.save(coursePo);

        if (isAdd) {
            coursePathDao.save(new CoursePathPo()
                    .setCpName(coursePo.getCName())
                    .setCpPath(coursePo.getWatchPath())
                    .setPlayAmount(3)
                    .setCpDuration(coursePo.getCTotalDuration())
                    .setThumbPath(OEConstant.DEFAULT_THUMB_PATH)
                    .setCId(save.getCId())
                    .setUploadTime(new Date())
                    .setLId(coursePo.getLId()));
        }

        return ResultCode.success("成功");
    }

    @ApiOperation("根据id删除课程信息")
    @WebProcess
    @DeleteMapping(value = "/course/deleteById")
    public ResultCode deleteById(@RequestParam("id") Integer id) {
        return ResultCode.success(courseService.deleteById(id));
    }

    @ApiOperation("批量根据id删除课程信息")
    @WebProcess
    @DeleteMapping(value = "/course/deleteByIds")
    public ResultCode deleteById(@RequestParam("ids") List<Integer> ids) {
        return ResultCode.success(courseService.deleteByIds(ids));
    }

    @ApiOperation("根据id修改是否上架")
    @GetMapping(value = "/course/updateCStatusById")
    public ResultCode updateCStatusById(@RequestParam("id") Integer id) {
        Boolean result = Optional.ofNullable(courseDao.findById(id))
                .map(vo -> vo.get())
                .map(coursePo -> coursePo.getCStatus())
                .orElseThrow();
        courseDao.updateCStatusById(!result, id);
        return ResultCode.success(result);
    }


}